package com.avengers.core.kit;


import com.avengers.common.bean.ApiResponse;
import com.jfinal.kit.HttpKit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * @author yu.wang
 * @since 2024/11/20 11:20
 **/
public class SelfApiService {
    public static final SelfApiService ME = new SelfApiService();
    private static final Logger logger = LoggerFactory.getLogger(SelfApiService.class);
    private static final String HOST = "https://www.17ex.com/";
    private static final String HOST_LOCAL = "http://127.0.0.1:58080/";
    private static final String AGENCY_ID = "2008";
    private static final String CLIENT_KEY = "2008";

    public static final Integer SUCCESS_CODE = 1;

    public ApiResponse<BigDecimal> queryUsdRate(String domain) {
        return queryUsdRate(domain, true);
    }

    public ApiResponse<BigDecimal> queryUsdRate(String domain, boolean useLocal) {
        Map<String, String> params = new HashMap<>();
        params.put("domain", domain);
        String syncResult = useLocal ? send(RouteSelf.aliyunRate, params) : send(HOST, RouteSelf.aliyunRate, params);
        return JsonKit.fromJson(syncResult, ApiResponse.class, BigDecimal.class);
    }

    public enum RouteSelf implements Route {
        aliyunRate("aliyun/rate");

        public final String value;

        RouteSelf(String value) {
            this.value = value;
        }

        @Override
        public String value() {
            return value;
        }
    }

    interface Route {
        String value();
    }

    private String send(Route route, Map<String, String> params) {
        try {
            String response = send(HOST_LOCAL, route, params);
            if (StringKit.notBlank(response)) {
                return response;
            }
        } catch (Exception e) {
            logger.error("query from {} error: {}", HOST_LOCAL, e.getMessage(), e);
        }
        return send(HOST, route, params);
    }

    private String send(String host, Route route, Map<String, String> params) {
        String url = host + "api/" + route.value();
        params.put("agency_id", AGENCY_ID);
        params.put("timestamp", "" + System.currentTimeMillis());

        String paramsStr = StringKit.mapToHttpParams(params, true);
        String signature = EncryptKit.sign(paramsStr, CLIENT_KEY);
        params.put("signature", signature);

        String requestJson = JsonKit.toGson(params);
        logger.info("self api route_{} request: {} ", route, requestJson);
        String response = TimeKit.logUsedTime(() -> HttpKit.post(url, null, StringKit.mapToHttpParams(params, true)), logger, "url_{} request: {}", url, requestJson);
        logger.info("self api route_{} params: {} response: {}", route, requestJson, response);
        return response;
    }
}
